package com.iqiao.platform.controller.admin;

import com.iqiao.common.util.date.ContextUtil;
import com.iqiao.common.web.result.JsonResult;
import com.iqiao.platform.model.Admin;
import com.iqiao.platform.model.Menu;
import com.iqiao.platform.service.AdminService;
import com.iqiao.platform.service.AuthService;
import com.iqiao.platform.service.MenuService;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by flt on 2017/10/31.
 */
@RestController
@RequestMapping(value = "auth")
public class AuthController {

    @Autowired
    private AuthService authService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private AdminService adminService;

    /**
     * 登录
     * @param request
     * @param response
     * @param map
     * @return
     */
    @PostMapping(value = "login")
    public JsonResult login(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestBody Map<String, Object> map) {
        String username = MapUtils.getString(map, "username");
        String password = MapUtils.getString(map, "password");
        String token = authService.login(username, password);
        Map<String, Object> doMap = new HashMap<>();
        doMap.put("token", token);
        return JsonResult.success(doMap);
    }

    /**
     * 获取登录用户信息
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "currentUser")
    public JsonResult currentUser(
            HttpServletRequest request,
            HttpServletResponse response){
        Long userId = ContextUtil.getCurrentUserId();
        if (null == userId) {
            return JsonResult.success();
        }
        Admin admin = adminService.findByUserId(userId);
        List<Menu> menuList = menuService.findByUserId(userId);
        Map<String, Object> doMap = new HashMap<>();
        doMap.put("name", admin.getNikename());
        doMap.put("menuList", menuList);
        return JsonResult.success(doMap);
    }

    @PostMapping(value = "refresh")
    public JsonResult refresh(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestBody Map<String, Object> map) {
        String refreshToken = MapUtils.getString(map, "refreshToken");
        String token = authService.refresh(refreshToken);
        Map<String, Object> doMap = new HashMap<>();
        doMap.put("token", token);
        return JsonResult.success(doMap);
    }
}
